define(['app', 'js/directive/listTree', 'js/filter/tree2Arr', 'datetime', 'pagination', 'autocomplete', 'filesaver', 'editor', 'fileupload', 'js/service/agupload'], function(app) {
    'use strict';
    /*manage knowledgeproperty*/
    app.controller('Messagesend', function($scope, crmConst, dataFactoryCRM, $q, $timeout, $rootScope, AgUpload, Upload, $http, $compile) {
        // $scope.qyapp = 'firstload';
        $scope.qyaccount;
        $scope.qyapplist;
        $scope.qyappobject = {};
        $scope.qyappsend = {};
        $scope.num = { pck: 1, sign: 2 };
        $scope.obj = {};
        $scope.arrchk = { chk: [], chksearch: [] };
        $scope.sign = { first: 1, second: 2, third: 3, forth: 4, fifth: 5 };
        $scope.signnum = 1;
        $scope.msgtype = '';
        $scope.delsign = 1;
        $scope.delsignimg = 1;
        $scope.the_end;
        $scope.the_endimg;
        $scope.count = 0;
        $scope.countimg = 0;
        $scope.file_mediaId;
        $scope.radioId;
        $scope.recordfilemedia;
        $scope.filemediaId;
        $scope.fivetabimg;
        $scope.fivetabmediaId;
        $scope.chk = { regularradiochk: 0, tempradiochk: 0 };
        // **************
        // section of img & article
        $scope.file;
        $scope.files;
        $scope.previewfile;
        $scope.previewfileimg;
        $rootScope.filelist = [{ img: 'dist/images/example_img.png', title: '', realpath: '', filepath: [], filename: [], filelistaddfiles: [], is_checked: '', author: '', abstract: '', content: '', url: '', media_id: '' }];
        $rootScope.filelistimg = [{ img: 'dist/images/example_img.png', title: '', realpath: '', filepath: [], filename: [], is_checked: '', abstract: '', content: '', url: '', media_id: '' }];
        $scope.postfilelist = [{}];
        $scope.tab = 'file';
        $rootScope.img = {};
        $scope.image;
        $scope.chkdisabled = true;
        $scope.thirdchkdisabled = true;
        $scope.multiplefilesupload = { multiplefiles: [] };
        $rootScope.addfilesparam = { addfiles: [] };
        $scope.numcount = [];
        $scope.seturls = 'Messagesend/uploadmultiplefiles';
        $scope.fileurl = 'Messagesend/fileupload'
        $scope.param = {};
        $scope.index = 1;
        $scope.previewimg;
        $scope.key = 0;
        $scope.keyimg = 0;
        $scope.transfile = {};
        $scope.filetitle;
        // **************
        $scope.knowledge_id;
        $scope.knowledge_spot_id;
        $scope.tabcondition;
        // **************
        $scope.messagesourcepage = {
            pageAll: 1,
            pageNow: 1,
            pageSize: $scope.psize,
            // pageSize: 5,
            k: 3892
        };
        $scope.messagesource = {};

        // add object of sending
        $scope.addobject = function() {
            var vchk;
            $timeout(function() {
                $('#multipledowntest').dropdown('clear');
                $scope.qyappsend = $scope.qyappobject;
                $timeout(function() {
                    $scope.arrchk.chk = $scope.arrchk.chksearch;
                    $('#multipledowntest').dropdown('set selected', $scope.arrchk.chk);
                    $("input[name='chk[]']").each(function() {
                        vchk = $(this).val();
                        if ($scope.arrchk.chk.indexOf(vchk) >= 0) {
                            $(this).prop('checked', true);
                        }
                    });
                })
            })
            $('#multipledowntest').dropdown({
                onChange: function(value, text, $selectedItem) {
                    $scope.arrchk.chk = value;
                    // console.log($scope.arrchk.chksearch);
                    $("input[name='chk[]']").each(function() {
                        vchk = $(this).val();
                        if ($scope.arrchk.chk.indexOf(vchk) >= 0) {
                            $(this).prop('checked', true);
                        }
                    });
                },

                onRemove: function(removedValue, removedText, $removedChoice) {
                    var ap = $scope.arrchk.chk.indexOf(removedValue);
                    $scope.arrchk.chk.splice(ap, 1);
                    // console.log($scope.arrchk.chksearch);
                    $("input[name='chk[]']").each(function() {
                        vchk = $(this).val();
                        if (vchk == removedValue) {
                            $(this).prop('checked', false);
                        }
                    });
                },
            });
            // $scope.tabchange($scope.num.pck);
            $('.add.modal').modal({
                autofocus: false,
                onApprove: function() {
                    $('#sendobjectdropdown').dropdown('clear');
                    $scope.arrchk.chksearch = $scope.arrchk.chk;
                    $('#sendobjectdropdown').dropdown('set selected', $scope.arrchk.chksearch);
                    // console.log($scope.arrchk.chksearch);
                }
            }).modal("show");
        }

        // get all object of qy_app
        $scope.getallobj = function(val) {
            var deferred = $q.defer();
            dataFactoryCRM.postDataByAPI('Messagesend/GetAllObj', { qyapp: $scope.qyapp }).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // checkbox click event
        $scope.addchk = function(index) {
            var ap = $scope.arrchk.chk.indexOf(index);
            if (ap === -1) {
                $scope.arrchk.chk.push(index);
                if ($scope.arrchk.chk.length != 0) {
                    $('#multipledowntest').dropdown('set selected', $scope.arrchk.chk);
                }
            } else {
                $scope.arrchk.chk.splice(ap, 1);
                $('#multipledowntest').dropdown('clear');
                $('#multipledowntest').dropdown('set selected', $scope.arrchk.chk);
            }
            // console.log($scope.arrchk.chk);
        }

        // change object in pachage
        $scope.changeobject = function(val) {
            console.log(11111);
            var ck;
            var substr = val.substring(0, 3);
            if (substr === 'pc_') {
                $scope.getsubscriberobject(val).then(function(d) {
                    $scope.obj = d.data;
                });
                var breadcrumb = '<a class="section" ng-click="tabchange(1)">全部套餐</a>' +
                    '<i class="right angle icon divider"></i>' +
                    '<div class="active section">归属套餐人员</div>';
                var $html = $compile(breadcrumb)($scope)
                $(".ui.tiny.breadcrumb").html($html);
                $("input[name='chk[]']").each(function() { $(this).prop('checked', false); });
                $timeout(function() {
                    if ($scope.arrchk.chk.indexOf(val) >= 0) {
                        $("input[name='chk[]']").each(function() {
                            $(this).prop('checked', true);
                            $(this).prop('disabled', true);
                        });
                    } else {
                        $("input[name='chk[]']").each(function() {
                            ck = $(this).val();
                            if ($scope.arrchk.chk.indexOf(ck) >= 0) {
                                $(this).prop('checked', true);
                            }
                        });
                    }
                }, 100)
            }
        }

        // tab change
        $scope.tabchange = function(key) {
            var ck;
            if (key == 1) {
                var breadcrumb = '<div class="section">全部套餐</div>';
                $(".ui.tiny.breadcrumb").html(breadcrumb)
                $scope.obj.length = 0;
                $scope.getallobj($scope.qyapp).then(function(d) {
                    $scope.obj = d.callfun;
                });
                $("input[name='chk[]']").each(function() { $(this).prop('checked', false); });
                $timeout(function() {
                    $("input[name='chk[]']").each(function() {
                        ck = $(this).val();
                        if ($scope.arrchk.chk.indexOf(ck) >= 0) {
                            $(this).prop('checked', true);
                        }
                    });
                }, 100)
            } else {
                // $scope.obj.length = 0;
                // $scope.obj = [{ k: '9', v: 'test9' }, { k: '10', v: 'test10' }];
                // $("input[name='chk[]']").each(function() { $(this).prop('checked', false); });
                // $timeout(function() {
                //     $("input[name='chk[]']").each(function() {
                //         ck = $(this).val();
                //         // console.log(ck);
                //         if ($scope.arrchk.chk.indexOf(ck) >= 0) {
                //             $(this).prop('checked', true);
                //         }
                //     });
                // }, 100);
            }
        }

        // get subscriber of qy_app
        $scope.getsubscriberobject = function(key) {
            var deferred = $q.defer();
            dataFactoryCRM.postDataByAPI('Messagesend/GetSubScriber', { obj: key }).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // get account of company
        $scope.CompanyAccount = function() {
            dataFactoryCRM.getDataByAPI('Messagesend/GetCompanyAccount').then(function(d) {
                if (d.rcode) {
                    $scope.companyaccount = d.data;
                }
            });
        }

        $scope.CompanyAccount();

        // watch qy_app 
        $scope.$watch('qyaccount', function(nv, ov) {
            if ($scope.qyaccount) {
                $timeout(function() {
                    $('#qyapp').dropdown('clear');
                    dataFactoryCRM.postDataByAPI('Messagesend/GetQyApp', { qyaccount: $scope.qyaccount }).then(function(d) {
                        if (d.rcode) {
                            // console.log(d.data);
                            $scope.qyapplist = d.data;
                        }
                    });
                })
            }
        });

        // watch to get all object
        $scope.$watch('qyapp', function(nv, ov) {
            var vchk;
            $('#sendobjectdropdown').dropdown({
                onChange: function(value, text, $selectedItem) {
                    $scope.arrchk.chksearch = value;
                    // console.log($scope.arrchk.chksearch);
                },

                onRemove: function(removedValue, removedText, $removedChoice) {
                    var ap = $scope.arrchk.chksearch.indexOf(removedValue);
                    $scope.arrchk.chksearch.splice(ap, 1);
                    // console.log($scope.arrchk.chksearch);
                }
            });
            // console.log($scope.arrchk.chksearch);
            $timeout(function() {
                if (nv != ov) {
                    $('#sendobjectdropdown').dropdown('clear');
                    $scope.arrchk.chksearch.length = 0;
                    $scope.getallobj($scope.qyapp).then(function(d) {
                        $scope.qyappobject = d.data;
                        $scope.obj = d.callfun;
                    });
                } else {
                    return true;
                }
            })
        });

        // multiple files upload
        $scope.multiple = function(k, v) {
            var deferred = $q.defer();
            $scope.multiplefilesupload.multiplefiles = k;
            $scope.multiplefilesupload.name = 'multiplefiles';
            Upload.upload({
                url: crmConst.BASE + crmConst.API + v,
                data: $scope.multiplefilesupload
            }).then(function(_data) {
                $scope.multiplefilesupload.status = 1;
                if (_data && _data.status == 200) {
                    deferred.resolve(_data.data);
                } else
                    deferred.reject("上传失败");
            });
            return deferred.promise;
        }

        // add first img of page
        $scope.addImgChange = function($fitem, key) {
            if ($fitem) {
                if (key == 1) {
                    $scope.filestore = $scope.file;
                } else {
                    // 
                }
                $scope.is_uploadingimg = true;
                $scope.multiple($fitem, $scope.seturls).then(function(d) {
                    $scope.is_uploadingimg = false;
                    if (key == 1) {
                        $rootScope.filelist[$scope.key]['realpath'] = d.view_path;
                    } else {
                        $rootScope.filelistimg[$scope.keyimg]['realpath'] = d.view_path;
                    }
                });
            } else {
                $scope.file = $scope.filestore;
            }
        }

        // add img into five tab
        $scope.addfivetabimg = function($img) {
            if ($img) {
                $scope.is_upimg = true;
                $scope.multiple($img, $scope.seturls).then(function(d) {
                    $scope.is_upimg = false;
                    $scope.fifthimgupload = d.view_path;
                });
            } else {
                // $scope.file = $scope.filestore;
            }
        }

        // display fisrt picture
        $scope.is_display = function() {
            if ($("input[name='addfirsttabchk']").prop('checked')) {
                $scope.checked = 1;
            } else {
                $scope.checked = 0;
            }
        }

        // add files of fisrt tab into array 
        $scope.addChange = function($file) {
            if ($file) {
                $scope.is_uploading = true;
                $scope.multiple($file, $scope.seturls).then(function(d) {
                    $rootScope.filelist[$scope.key]['filepath'].push(d.view_path);
                    $rootScope.filelist[$scope.key]['filename'].push(d.source_name);
                    $rootScope.filelist[$scope.key]['filelistaddfiles'].push(d.source_name);
                    $rootScope.addfilesparam.addfiles = $rootScope.filelist[$scope.key]['filelistaddfiles'];
                    $scope.is_uploading = false;
                });
            } else {
                $scope.import_file_error("选择文件格式错误");
            }
        };

        //multiple files import error verify
        $scope.import_file_error = function(_msg) {
            $scope.import_pays_error = _msg;
            $timeout(function() {
                $scope.import_pays_error = '';
            }, 2000);
        };

        // del first tab files in array
        $scope.delFile = function() {
            var index = this.$index;
            $scope.addfilesparam.addfiles.splice(index, 1);
            $rootScope.filelist[$scope.key]['filepath'].splice(index, 1);
            $rootScope.filelist[$scope.key]['filename'].splice(index, 1);
            // console.log($scope.filelist);
        }

        // del firstimg
        $scope.delFirstImg = function() {
            $rootScope.filelist[$scope.key]['img'] = '';
            $scope.previewfile = '';
        }

        // watch first tab img
        $scope.$watch('file', function(nv, ov) {
            if (nv != ov) {
                $scope.chkdisabled = false;
                $scope.previewfile = $scope.file;
                $rootScope.filelist[$scope.key]['img'] = window.URL.createObjectURL($scope.file);
                $scope.multipleimgartical();
                if (!$scope.file) {
                    $("input[name='addfirsttabchk']").prop('checked', false);
                    $scope.checked = 0;
                    $scope.chkdisabled = true;
                } else {
                    $scope.chkdisabled = false;
                }
            } else {
                return true;
            }
        });

        // watch first tab img
        $scope.$watch('fileimg', function(nv, ov) {
            if (nv != ov) {
                $scope.thirdchkdisabled = false;
                $scope.previewfileimg = $scope.fileimg;
                $timeout(function() {
                    $rootScope.filelistimg[$scope.keyimg]['img'] = window.URL.createObjectURL($scope.fileimg);
                    $scope.multipleimgarticalimg();
                    if (!$scope.fileimg) {
                        $("input[name='addthirdtabchk']").prop('checked', false);
                        $scope.thirdchecked = 0;
                        $scope.thirdchkdisabled = true;
                    } else {
                        $scope.thirdchkdisabled = false;
                    }
                })
            } else {
                return true;
            }
        });

        // watch title change
        $scope.$watch('title', function(nv, ov) {
            if ($scope.delsign == 1) {
                $rootScope.filelist[$scope.key]['title'] = $scope.title;
                $scope.multipleimgartical();
            }
        });

        // first tab in multiple img-artical
        $scope.multipleimgartical = function() {
            if ($scope.filelist[0].img) {
                var str = '<div class="coverimg">' +
                    '<div class="covertext" ng-click="tabpreview(0)">' +
                    '<div ng-repeat="(k,v) in filelist">' +
                    '<img ng-if="k == 0" ngf-src="v.img" />' +
                    '<div ng-if="k == 0" class="covertitle">{{v.title}}</div>' +
                    '</div>' +
                    '</div>';
            } else {
                var str = '<div class="coverimg">' +
                    '<div class="covertext"  ng-click="tabpreview(0)">' +
                    '<p>封面图片</p>' +
                    '<p>推荐尺寸:900像素*500像素</p>' +
                    '</div>' +
                    // '<div class="covertitle">标题</div>' +
                    '<div ng-repeat="(k,v) in filelist">' +
                    '<div ng-if="k == 0" class="covertitle">{{v.title}}</div>' +
                    '</div>' +
                    '</div>';
            }
            var $html = $compile(str)($scope);
            $('#top1').html($html);
        }

        // watch title change
        $scope.$watch('author', function(nv, ov) {
            if ($scope.delsign == 1)
                $rootScope.filelist[$scope.key]['author'] = $scope.author;
        });

        // watch title change
        $scope.$watch('abstract', function(nv, ov) {
            if ($scope.delsign == 1)
                if (!$scope.abstract) {

                } else {
                    $rootScope.filelist[$scope.key]['abstract'] = $scope.abstract;
                }

        });

        // watch title change
        $scope.$watch('url', function(nv, ov) {
            if ($scope.delsign == 1)
                $rootScope.filelist[$scope.key]['url'] = $scope.url;
        });

        // watch checked change
        $scope.$watch('checked', function(nv, ov) {
            if ($scope.delsign == 1) {
                if ($scope.checked) {
                    $rootScope.filelist[$scope.key]['is_checked'] = $scope.checked;
                } else {
                    $rootScope.filelist[$scope.key]['is_checked'] = 0;
                }
                // console.log($rootScope.filelist);
            }
        });

        // watch add richcontent
        $scope.$watch('templete', function(nv, ov) {
            if (!nv || nv == '<p><br></p>') {
                $('#add_tempalte').val('');
            } else {
                $('#add_tempalte').val($scope.templete);
                $rootScope.filelist[$scope.key]['content'] = $scope.templete;
            }
        });


        // add img preview
        $scope.addimgpreview = function() {
            if ($rootScope.filelist.length < 6) {
                $rootScope.filelist.push({ img: '', title: '', realpath: '', filepath: [], filename: [], filelistaddfiles: [], is_checked: '', author: '', abstract: '', content: '', url: '' });
                $scope.previewfile = '';
                $scope.delsign = 1;
                $scope.initvalueofmodel();
                $('#items1').empty();
                for (var i = 0; i < $rootScope.filelist.length; i++) {
                    $scope.key = i;
                    if (i == 0) {
                        if ($scope.filelist[0].img) {
                            var str = '<div class="coverimg">' +
                                '<div class="covertext" ng-click="tabpreview(0)">' +
                                '<div ng-repeat="(k,v) in filelist">' +
                                '<img ng-if="k == 0" ngf-src="v.img" />' +
                                '<div ng-if="k == 0" class="covertitle">{{v.title}}</div>' +
                                '</div>' +
                                '</div>';
                        } else {
                            var str = '<div class="coverimg">' +
                                '<div class="covertext"  ng-click="tabpreview(0)">' +
                                '<p>封面图片</p>' +
                                '<p>推荐尺寸:900像素*500像素</p>' +
                                '</div>' +
                                '<div ng-repeat="(k,v) in filelist">' +
                                '<div ng-if="k == 0" class="covertitle">{{v.title}}</div>' +
                                '</div>' +
                                '</div>';
                        }
                        var $html = $compile(str)($scope);
                        $('#top1').html($html);
                    } else {
                        var str = '<div class="show_item" ng-click="tabpreview(' + i + ')">' +
                            '<div class="box clearfix">' +
                            '<div ng-repeat="(k,v) in filelist">' +
                            '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                            '<img class="img" ng-if="k == ' + i + '" ngf-src="v.img" />' +
                            '</div>' +
                            // '<img class="img"  src="' + $scope.filelist[i].img + '" />' +
                            '</div>' +
                            '<div class="item_action">' +
                            // '<span>' +
                            // '<i class="large angle up icon"></i>' +
                            // '<i class="large angle down icon"></i>' +
                            // '</span>' +
                            '<i class="large trash icon" ng-click="deleteShowItem($event,' + i + ')"></i>' +
                            '</div>' +
                            '</div>';
                        var $html = $compile(str)($scope);
                        $('#items1').append($html);
                    }
                }
                if ($rootScope.filelist.length == 6) {
                    $('#bottom1').hide();
                }
            }
        }

        // clear the value of ng-model
        $scope.initvalueofmodel = function() { //why clear function doesn't run
            $scope.title = '';
            $scope.author = '';
            $scope.abstract = '';
            $scope.templete = '';
            $scope.url = '';
            $('#addfirsttabchk').prop('checked', false);
            $rootScope.addfilesparam.addfiles = [{}];
        }

        // delete img upload
        $scope.deleteShowItem = function($event, key) {
            $scope.delsign = 2;
            $scope.previewfile = '';
            $scope.title = '';
            $scope.author = '';
            $scope.abstract = '';
            $scope.templete = '';
            $scope.url = '';
            $('#addfirsttabchk').prop('checked', false);
            $scope.addfilesparam.addfiles = [{}];
            $rootScope.filelist.splice(key, 1);
            $($event.target).closest('.show_item').remove();
            $('#items1').empty();
            for (var i = 1; i < $rootScope.filelist.length; i++) {
                $scope.key = i;
                var str = '<div class="show_item" ng-click="tabpreview(' + i + ')">' +
                    '<div class="box clearfix">' +
                    '<div ng-repeat="(k,v) in filelist">' +
                    '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                    '<img class="img" ng-if="k == ' + i + '" ngf-src="v.img" />' +
                    '</div>' +
                    '</div>' +
                    '<div class="item_action">' +
                    '<i class="large trash icon" ng-click="deleteShowItem($event,' + i + ')"></i>' +
                    '</div>' +
                    '</div>';
                var $html = $compile(str)($scope);
                $('#items1').append($html);
            }
            $('#bottom1').show();
        }

        // tab preview
        $scope.tabpreview = function(key) {
            $scope.key = key;
            $scope.delsign = 1;
            if ($rootScope.filelist[key]['is_checked']) {
                $('#addfirsttabchk').prop('checked', true);
            } else {
                $('#addfirsttabchk').prop('checked', false);
            }
            $scope.checked = $rootScope.filelist[key]['is_checked'];
            $scope.previewfile = $rootScope.filelist[key]['img'];
            $scope.title = $rootScope.filelist[key]['title'];
            $scope.author = $rootScope.filelist[key]['author'];
            $scope.abstract = $rootScope.filelist[key]['abstract'];
            $scope.templete = $rootScope.filelist[key]['content'];
            $scope.url = $rootScope.filelist[key]['url'];
            $scope.templete = $rootScope.filelist[key]['content'];
            $rootScope.addfilesparam.addfiles = [{}];
            $rootScope.addfilesparam.addfiles = $rootScope.filelist[key]['filelistaddfiles'];
        }

        // send message list
        $scope.messagesendlist = function(index, $event) {
            $scope.signnum = index;
            var url = 'Messagesend/Index';
            if (index == 1) {
                $scope.msgtype = 'image';
                $scope.count = 0;
                for (var i = 0; i < $rootScope.filelist.length; i++) {
                    $scope.wechatfileupload($rootScope.filelist[$scope.count].realpath, $scope.fileurl, $scope.msgtype).then(function(d) {
                        $rootScope.filelist[$scope.count].thumb_media_id = d.data.media_id;
                        $scope.the_end = $scope.count + 1;
                        $scope.count = $scope.count + 1;
                    });
                }
                $scope.$watch('the_end', function(nv, ov) {
                    $timeout(function() {
                        $scope.msgtype = 'mpnews';
                        if ($scope.arrchk.chksearch.length != 0) {
                            if ($scope.the_end == $rootScope.filelist.length) {
                                dataFactoryCRM.postDataByAPI('Messagesend/Index', { msgtype: $scope.msgtype, searchobj: $scope.arrchk.chksearch, mpnews: { articles: $rootScope.filelist }, qy_code: $scope.qyaccount, qy_app_id: $scope.qyapp, k: index, radio: $scope.chk, chk: $scope.safechk }).then(function(d) {
                                    if (d.returnDate.rcode == 1) {
                                        $scope.title = '';
                                        $scope.author = '';
                                        $scope.abstract = '';
                                        $scope.templete = '';
                                        $scope.url = '';
                                        $scope.previewfile = '';
                                        $scope.delsign = 1;
                                        $scope.count = 0;
                                        $scope.key = 0;
                                        $scope.filelist.splice(0, $scope.filelist.length);
                                        $scope.filelist.push({ img: 'dist/images/example_img.png', title: '', realpath: '', filepath: [], filename: [], is_checked: '', abstract: '', content: '', url: '', media_id: '' });
                                        // console.log($scope.filelist);
                                        for (var i = 0; i < $rootScope.filelist.length; i++) {
                                            $scope.key = i;
                                            if (i == 0) {
                                                if ($scope.filelist[0].img) {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext" ng-click="tabpreview(0)">' +
                                                        '<div ng-repeat="(k,v) in filelist">' +
                                                        '<img ng-if="k == 0" ngf-src="v.img" />' +
                                                        '<div ng-if="k == 0" class="covertitle">{{v.title}}</div>' +
                                                        '</div>' +
                                                        '</div>';
                                                } else {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext"  ng-click="tabpreview(0)">' +
                                                        '<p>封面图片</p>' +
                                                        '<p>推荐尺寸:900像素*500像素</p>' +
                                                        '</div>' +
                                                        // '<div class="covertitle">标题</div>' +
                                                        '<div ng-repeat="(k,v) in filelist">' +
                                                        '<div ng-if="k == 0" class="covertitle">{{v.title}}</div>' +
                                                        '</div>' +
                                                        '</div>';
                                                }
                                                var $html = $compile(str)($scope);
                                                $('#top1').html($html);
                                                $("#items1").empty();
                                            }
                                        }
                                    }
                                });
                            }
                        } else {
                            console.log('请将信息填写完整');
                        }
                    })
                })
            } else if (index == 2) {
                $scope.msgtype = 'file';
                if (!$scope.recordfilemedia || $scope.recordfilemedia != $scope.file_view_path) {
                    $scope.wechatfileupload($scope.file_view_path, $scope.fileurl, $scope.msgtype).then(function(d) {
                        $scope.recordfilemedia = $scope.file_view_path;
                        $scope.file_mediaId = d.data.media_id;
                    });
                    $scope.$watch('file_mediaId', function(nv, ov) {
                        if ($scope.file_mediaId && $scope.filemediaId != $scope.file_mediaId && $scope.arrchk.chksearch.length != 0) {
                            $scope.filemediaId = $scope.file_mediaId;
                            dataFactoryCRM.postDataByAPI('Messagesend/Index', { msgtype: $scope.msgtype, file: { media_id: $scope.file_mediaId }, searchobj: $scope.arrchk.chksearch, qy_code: $scope.qyaccount, qy_app_id: $scope.qyapp, k: index, radio: $scope.chk, chk: $scope.safechk }).then(function(d) {
                                console.log(d);
                            });
                        } else {
                            console.log('请将信息填写完整');
                        }
                    })
                }
            } else if (index == 3) {
                $scope.msgtype = 'image';
                $scope.countimg = 0;
                for (var i = 0; i < $rootScope.filelistimg.length; i++) {
                    $scope.wechatfileupload($rootScope.filelistimg[$scope.countimg].realpath, $scope.fileurl, $scope.msgtype).then(function(d) {
                        $rootScope.filelistimg[$scope.countimg].thumb_media_id = d.data.media_id;
                        $scope.the_endimg = $scope.countimg + 1;
                        $scope.countimg = $scope.countimg + 1;
                    });
                }
                $scope.$watch('the_endimg', function(nv, ov) {
                    $timeout(function() {
                        $scope.msgtype = 'mpnews';
                        if ($scope.arrchk.chksearch.length != 0) {
                            if ($scope.the_endimg == $rootScope.filelistimg.length) {
                                dataFactoryCRM.postDataByAPI('Messagesend/Index', { msgtype: $scope.msgtype, searchobj: $scope.arrchk.chksearch, mpnews: { articles: $rootScope.filelistimg }, qy_code: $scope.qyaccount, qy_app_id: $scope.qyapp, k: index, radio: $scope.chk, chk: $scope.safechk }).then(function(d) {
                                    if (d.returnDate.rcode == 1) {
                                        $scope.urltitle = '';
                                        $scope.urlabstract = '';
                                        $scope.outerUrl = '';
                                        $scope.the_endimg = '';
                                        $scope.previewfileimg = '';
                                        $scope.delsignimg = 1;
                                        $scope.countimg = 0;
                                        $scope.keyimg = 0;
                                        // $('#addthirdtabchk').prop('checked', false);
                                        $scope.filelistimg.splice(0, $scope.filelistimg.length);
                                        $scope.filelistimg.push({ img: 'dist/images/example_img.png', title: '', realpath: '', filepath: [], filename: [], is_checked: '', abstract: '', content: '', url: '', media_id: '' });
                                        for (var i = 0; i < $rootScope.filelistimg.length; i++) {
                                            $scope.keyimg = i;
                                            if (i == 0) {
                                                if ($scope.filelistimg[0].img) {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext" ng-click="tabpreviewimg(0)">' +
                                                        '<div ng-repeat="(k,v) in filelistimg">' +
                                                        '<img ng-if="k == 0" ngf-src="v.img" />' +
                                                        '<div class="title fl" ng-if="k == 0">{{v.title}}</div>' +
                                                        '</div>' +
                                                        '</div>';
                                                } else {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext"  ng-click="tabpreviewimg(0)">' +
                                                        '<p>封面图片</p>' +
                                                        '<p>推荐尺寸:900像素*500像素</p>' +
                                                        '</div>' +
                                                        '<div ng-repeat="(k,v) in filelistimg">' +
                                                        '<div class="title fl" ng-if="k == 0">{{v.title}}</div>' +
                                                        '</div>' +
                                                        '</div>';
                                                }
                                                var $html = $compile(str)($scope);
                                                $('#top3').html($html);
                                                $("#items3").empty();
                                            }
                                        }
                                    }
                                });
                            }
                        } else {
                            console.log('请将信息填写完整');
                        }
                    })
                })
            } else if (index == 4) {
                $scope.msgtype = 'text';
                if ($scope.arrchk.chksearch.length != 0 && $scope.textcontent) {
                    dataFactoryCRM.postDataByAPI('Messagesend/Index', { msgtype: $scope.msgtype, searchobj: $scope.arrchk.chksearch, text: { content: $scope.textcontent }, qy_code: $scope.qyaccount, qy_app_id: $scope.qyapp, k: index, radio: $scope.chk, chk: $scope.safechk }).then(function(d) {
                        if (d.returnDate.rcode == 1) {
                            $scope.textcontent = ''
                        } else {
                            $('<div class="ui small modal modal2" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge red warning outline icon"></i>' +
                                '<p style="padding-top: 15px;"></p>发送消息失败</p>' + '</div></div>'
                            ).modal({ closable: false }).modal('show');
                        }
                        console.log(d);
                    });
                } else {
                    console.log('请将信息填写完整');
                }
            } else {
                $scope.msgtype = 'image';
                if (!$scope.fivetabimg || $scope.fivetabimg != $scope.fifthimgupload) {
                    $scope.wechatfileupload($scope.fifthimgupload, $scope.fileurl, $scope.msgtype).then(function(d) {
                        $scope.img_mediaId = d.data.media_id;
                        $scope.fivetabimg = $scope.fifthimgupload;
                    });
                }
                $scope.$watch('img_mediaId', function(nv, ov) {
                    if ($scope.img_mediaId && $scope.fivetabmediaId != $scope.img_mediaId && $scope.arrchk.chksearch.length != 0) {
                        $scope.fivetabmediaId = $scope.img_mediaId;
                        dataFactoryCRM.postDataByAPI('Messagesend/Index', { msgtype: $scope.msgtype, img: { media_id: $scope.img_mediaId }, searchobj: $scope.arrchk.chksearch, qy_code: $scope.qyaccount, qy_app_id: $scope.qyapp, k: index, radio: $scope.chk, chk: $scope.safechk }).then(function(d) {
                            console.log(d);
                        });
                    } else {
                        console.log('请将信息填写完整');
                    }
                })
            }
        }

        // file upload in file tab
        $scope.addUpload = function($files) {
            if ($files) {
                $scope.filetitle = $scope.transfile.name;
                $scope.is_uploading = true;
                $scope.multiple($files, $scope.seturls).then(function(d) {
                    $scope.is_uploading = false;
                    $scope.file_view_path = d.view_path;
                });
            } else {
                // $scope.filetitle = $scope.filetitle;
            }
        }

        // multiple files upload
        $scope.wechatfileupload = function(m, v, k) {
            var deferred = $q.defer();
            Upload.upload({
                url: crmConst.BASE + crmConst.API + v,
                data: { 'path': m, 'type': k }
            }).then(function(_data) {
                if (_data) {
                    deferred.resolve(_data.data);
                } else
                    deferred.reject("上传失败");
            });
            return deferred.promise;
        }

        // tab change
        $scope.messagesendlistnum = function(index) {
            $scope.signnum = index;
        }
        $scope.messagesendlistnum($scope.signnum);

        // choice from knowledge property
        $scope.choicefromkp = function(index) {
            $scope.KnowledgeRightList().then(function(d) {
                $scope.KnowledgeSource = d.data;
            });
            if (index == 1 || index == 2 || index == 3) {
                $('.delivery.modal').modal({
                    autofocus: false,
                    observeChanges: true,
                    closable: false,
                    onApprove: function() {
                        if (index == 1) {
                            dataFactoryCRM.postDataByAPI('Messagesend/GetKnowledgeMsg', { knowledgeId: $scope.radioId, msg_type: $scope.msg_type }).then(function(d) {
                                if (d.rcode == 1) {
                                    if ($rootScope.filelist.length < 6) {
                                        $scope.delsign = 1;
                                        var sublength = $rootScope.filelist.length - 1;
                                        if (d.data.first_page_show == 1) {
                                            $('#addfirsttabchk').prop('checked', true);
                                        } else {
                                            $('#addfirsttabchk').prop('checked', false);
                                        }
                                        $rootScope.filelist[sublength]['is_checked'] = d.data.first_page_show;
                                        $rootScope.filelist[sublength]['img'] = d.data.first_page_image;
                                        $rootScope.filelist[sublength]['title'] = d.data.title;
                                        $rootScope.filelist[sublength]['author'] = d.data.pen_name;
                                        $rootScope.filelist[sublength]['abstract'] = d.data.abstract;
                                        $rootScope.filelist[sublength]['content'] = d.data.content;
                                        $rootScope.filelist[sublength]['url'] = d.data.artical_url;

                                        $scope.checked = d.data.first_page_show;
                                        $scope.previewfile = d.data.first_page_image;
                                        $scope.title = d.data.title;
                                        $scope.author = d.data.pen_name;
                                        $scope.abstract = d.data.abstract;
                                        $scope.templete = d.data.content;
                                        $scope.url = d.data.artical_url;
                                        $rootScope.addfilesparam.addfiles = [{}];
                                        // $rootScope.addfilesparam.addfiles = $rootScope.filelist[length - 1]['filelistaddfiles'];
                                        $('#items1').empty();
                                        for (var i = 0; i < $rootScope.filelist.length; i++) {
                                            $scope.key = i;
                                            if (i == 0) {
                                                if ($scope.filelist[0].img) {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext" ng-click="tabpreview(0)">' +
                                                        '<div ng-repeat="(k,v) in filelist">' +
                                                        '<img ng-if="k == 0" ngf-src="v.img" />' +
                                                        '<div class="covertitle"  ng-if="k == ' + i + '">{{v.title}}</div>' +
                                                        '</div>' +
                                                        '</div>';
                                                } else {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext"  ng-click="tabpreview(0)">' +
                                                        '<p>封面图片</p>' +
                                                        '<p>推荐尺寸:900像素*500像素</p>' +
                                                        '</div>' +
                                                        '<div class="covertitle">标题</div>' +
                                                        '</div>';
                                                }
                                                var $html = $compile(str)($scope);
                                                $('#top1').html($html);
                                            } else {
                                                var str = '<div class="show_item" ng-click="tabpreview(' + i + ')">' +
                                                    '<div class="box clearfix">' +
                                                    '<div ng-repeat="(k,v) in filelist">' +
                                                    '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                                                    '<img class="img" ng-if="k == ' + i + '" ngf-src="v.img" />' +
                                                    '</div>' +
                                                    // '<img class="img"  src="' + $scope.filelist[i].img + '" />' +
                                                    '</div>' +
                                                    '<div class="item_action">' +
                                                    '<span>' +
                                                    '<i class="large angle up icon"></i>' +
                                                    '<i class="large angle down icon"></i>' +
                                                    '</span>' +
                                                    '<i class="large trash icon" ng-click="deleteShowItem($event,' + i + ')"></i>' +
                                                    '</div>' +
                                                    '</div>';
                                                var $html = $compile(str)($scope);
                                                $('#items1').append($html);
                                            }
                                        }
                                        if ($rootScope.filelist.length == 6) {
                                            $('#bottom1').hide();
                                        }
                                    }
                                } else {
                                    // deferred.reject('call function error');
                                }
                            });
                        } else if (index == 2) {
                            dataFactoryCRM.postDataByAPI('Messagesend/GetKnowledgeMsg', { knowledgeId: $scope.radioId, msg_type: $scope.signnum }).then(function(d) {
                                if (d.rcode == 1) {
                                    $scope.filetitle = d.data.file_original_name;
                                    $scope.transfile.name = d.data.file_original_name;
                                    $scope.file_view_path = d.data.knowledge_file_name;
                                }
                            });
                        } else {
                            dataFactoryCRM.postDataByAPI('Messagesend/GetKnowledgeMsg', { knowledgeId: $scope.radioId, msg_type: $scope.signnum }).then(function(d) {
                                if (d.rcode == 1) {
                                    if ($rootScope.filelistimg.length < 6) {
                                        $scope.delsignimg = 1;
                                        var sublengthimg = $rootScope.filelistimg.length - 1;
                                        if (d.data.first_page_show == 1) {
                                            $('#addthirdtabchk').prop('checked', true);
                                        } else {
                                            $('#addthirdtabchk').prop('checked', false);
                                        }
                                        $rootScope.filelistimg[sublengthimg]['is_checked'] = d.data.first_page_show;
                                        $rootScope.filelistimg[sublengthimg]['img'] = d.data.first_page_image;
                                        $rootScope.filelistimg[sublengthimg]['title'] = d.data.title;
                                        $rootScope.filelistimg[sublengthimg]['abstract'] = d.data.abstract;
                                        $rootScope.filelistimg[sublengthimg]['url'] = d.data.artical_url;
                                        $scope.thirdchecked = d.data.first_page_show;
                                        $scope.previewfileimg = d.data.first_page_image;
                                        $scope.urltitle = d.data.title;
                                        $scope.urlabstract = d.data.abstract;
                                        $scope.outerUrl = d.data.artical_url;
                                        $('#items3').empty();
                                        for (var i = 0; i < $rootScope.filelistimg.length; i++) {
                                            $scope.keyimg = i;
                                            if (i == 0) {
                                                if ($scope.filelistimg[0].img) {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext" ng-click="tabpreviewimg(0)">' +
                                                        '<div ng-repeat="(k,v) in filelistimg">' +
                                                        '<img ng-if="k == 0" ngf-src="v.img" />' +
                                                        '</div>' +
                                                        '<div class="covertitle">标题</div>' +
                                                        '</div>';
                                                } else {
                                                    var str = '<div class="coverimg">' +
                                                        '<div class="covertext"  ng-click="tabpreviewimg(0)">' +
                                                        '<p>封面图片</p>' +
                                                        '<p>推荐尺寸:900像素*500像素</p>' +
                                                        '</div>' +
                                                        '<div class="covertitle">标题</div>' +
                                                        '</div>';
                                                }
                                                var $html = $compile(str)($scope);
                                                $('#top3').html($html);
                                            } else {
                                                var str = '<div class="show_item" ng-click="tabpreviewimg(' + i + ')">' +
                                                    '<div class="box clearfix">' +
                                                    '<div ng-repeat="(k,v) in filelistimg">' +
                                                    '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                                                    '<img class="img" ng-if="k == ' + i + '" ngf-src="v.img" />' +
                                                    '</div>' +
                                                    '</div>' +
                                                    '<div class="item_action">' +
                                                    '<i class="large trash icon" ng-click="deleteShowItemimg($event,' + i + ')"></i>' +
                                                    '</div>' +
                                                    '</div>';
                                                var $html = $compile(str)($scope);
                                                $('#items3').append($html);
                                            }
                                        }
                                        if ($rootScope.filelistimg.length == 6) {
                                            $('#bottom3').hide();
                                        }
                                    }
                                }
                            });
                        }

                    }
                }).modal("show");
            }

        }

        // show knowledgeRight list
        $scope.KnowledgeRightList = function() {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Messagesend/GetKnowledgeData').then(function(d) {
                if (d.rcode == 1) {
                    $scope.KnowledgeNodeTree(d.data);
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // knowledge node tree
        $scope.KnowledgeNodeTree = function(arr) {
            var changArr = [];
            var newArr = ["00"];
            for (var i = 0; i < arr.length; i++) {
                changArr.push(arr[i]['code']);
            }
            for (var i = 1; i < arr.length; i++) {
                if (changArr[i].length > 4) {
                    var num = changArr[i].length - 4;
                    var a = changArr[i].substring(0, changArr[i].length - num);
                    if (changArr.indexOf(a) == -1) {
                        newArr.push(a);
                    } else {
                        newArr.push(changArr[i]);
                    }
                } else {
                    newArr.push(changArr[i]);
                }
            }
            var treeStr = '<div class="ui accordion">'
            for (var i = 0; i < arr.length; i++) {
                if (i == 0) {
                    treeStr += '<div class="active title" ><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length > newArr[i - 1].length) {
                    var time = (newArr[i].length - newArr[i - 1].length) / 2;
                    if (time > 1) {
                        for (var k = 1; k < time; k++) {
                            treeStr += '<div class="active content"><div class="accordion">';
                        }
                    }
                    treeStr += '<div class="active content"><div class="accordion"><div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',$event,' + $scope.signnum + ')"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length == newArr[i - 1].length && newArr[i].length != 2) {
                    treeStr += '<div class="active content"></div><div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',$event,' + $scope.signnum + ')"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length == newArr[i - 1].length && newArr[i].length == 2) {
                    treeStr += '<div class="active content"></div><div class="active title"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length < newArr[i - 1].length && newArr[i].length != 2) {
                    treeStr += '<div class="active content"></div>';
                    var num = (newArr[i - 1].length - newArr[i].length) / 2;
                    for (var j = 0; j < num; j++) {
                        treeStr += '</div></div>';
                    }
                    treeStr += '<div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',$event,' + $scope.signnum + ')"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length < newArr[i - 1].length && newArr[i].length == 2) {
                    treeStr += '<div class="active content"></div>';
                    var num = (newArr[i - 1].length - newArr[i].length) / 2;
                    for (var j = 0; j < num; j++) {
                        treeStr += '</div></div>';
                    }
                    treeStr += '<div class="active title"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                }
                if (i == arr.length - 1) {
                    treeStr += '<div class="active content"></div>';
                }
            }
            var $html = $compile(treeStr)($scope);
            $('.treemenu').html($html);
            $(".treemenu .content").each(function() {
                if ($(this).text() == "") {
                    $(this).prev().find(".icon").removeClass('dropdown').addClass('small minus');
                }
            });
            $('.treemenu .ui.accordion').accordion({
                exclusive: false,
                selector: {
                    trigger: '.title .icon'
                }
            });
            $('.treemenu .ui.accordion').find('.accordion').css("marginLeft", "20px");
        }

        $scope.KnowledgeDatalist = function() {
            if ($scope.tabcondition) {
                $scope.knowledge_id = $scope.tabcondition;
                $scope.knowledge_spot_id = $scope.tabcondition;
                dataFactoryCRM.getDataByAPI('Messagesend/knowledgelist?knowledge_spot_id=' + $scope.knowledge_spot_id + '&radioId=' + $scope.signnum + '&psize=' + $scope.messagesourcepage.pageSize + '&p=' + $scope.messagesourcepage.pageNow).then(function(_d) {
                    if (_d.rcode == 1) {
                        $scope.messagesourcepage.pageSize = _d.psize;
                        $scope.messagesourcepage.pageAll = _d.pall;
                        $scope.messagesourcepage.pageNow = _d.p;
                        $scope.messagesource = _d.data;
                    } else {
                        $scope.messagesource = '';
                        $scope.messagesourcepage.pageSize = $scope.psize;
                        $scope.messagesourcepage.pageAll = 1;
                        $scope.messagesourcepage.pageNow = 1;
                    }
                });
            } else {
                setTimeout(function() { //why need twice settimeout
                    $scope.KnowledgeRightList().then(function(d) {
                        $scope.KnowledgeSource = d.data;
                    });
                    $scope.is_picture = 1;
                }, 100)
            }
        }

        // condition judged
        $scope.condition = function(k, $event) {
            $('.treemenu .title').removeClass('checked');
            $($event.target).addClass('checked');
            $scope.tabcondition = k;
            $scope.KnowledgeDatalist();
        }

        // radio checked
        $scope.radiounchecded = function(k) {
            $scope.radioId = k;
        }

        // del fifth img
        $scope.delfifthimg = function() {
            $scope.uploadimg = '';
        }

        // add img in five tab
        $scope.addimgpreviewinfivetab = function() {
            if ($rootScope.filelistimg.length < 6) {
                $rootScope.filelistimg.push({ img: '', title: '', realpath: '', filepath: [], filename: [], is_checked: '', abstract: '', content: '', url: '' });
                // 
                $scope.previewfileimg = '';
                $scope.delsignimg = 1;
                $scope.initvalueoffivetabmodel();
                $('#items3').empty();
                for (var i = 0; i < $rootScope.filelistimg.length; i++) {
                    $scope.keyimg = i;
                    if (i == 0) {
                        if ($scope.filelistimg[0].img) {
                            var str = '<div class="coverimg">' +
                                '<div class="covertext" ng-click="tabpreviewimg(0)">' +
                                '<div ng-repeat="(k,v) in filelistimg">' +
                                '<img ng-if="k == 0" ngf-src="v.img" />' +
                                '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                                '</div>' +
                                '</div>';
                        } else {
                            var str = '<div class="coverimg">' +
                                '<div class="covertext"  ng-click="tabpreviewimg(0)">' +
                                '<p>封面图片</p>' +
                                '<p>推荐尺寸:900像素*500像素</p>' +
                                '</div>' +
                                '<div ng-repeat="(k,v) in filelistimg">' +
                                '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                                '</div>' +
                                '</div>';
                        }
                        var $html = $compile(str)($scope);
                        $('#top3').html($html);
                    } else {
                        var str = '<div class="show_item" ng-click="tabpreviewimg(' + i + ')">' +
                            '<div class="box clearfix">' +
                            '<div ng-repeat="(k,v) in filelistimg">' +
                            '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                            '<img class="img" ng-if="k == ' + i + '" ngf-src="v.img" />' +
                            '</div>' +
                            '</div>' +
                            '<div class="item_action">' +
                            '<i class="large trash icon" ng-click="deleteShowItemimg($event,' + i + ')"></i>' +
                            '</div>' +
                            '</div>';
                        var $html = $compile(str)($scope);
                        $('#items3').append($html);
                    }
                }
                if ($rootScope.filelistimg.length == 6) {
                    $('#bottom3').hide();
                }
            }
        }

        // tab preview img
        $scope.tabpreviewimg = function(key) {
            $scope.keyimg = key;
            $scope.delsignimg = 1;
            if ($rootScope.filelistimg[key]['is_checked']) {
                $('#addthirdtabchk').prop('checked', true);
            } else {
                $('#addthirdtabchk').prop('checked', false);
            }
            $scope.thirdchecked = $rootScope.filelistimg[key]['is_checked'];
            $scope.previewfileimg = $rootScope.filelistimg[key]['img'];
            $scope.urlabstract = $rootScope.filelistimg[key]['abstract'];
            $scope.outerUrl = $rootScope.filelistimg[key]['url'];
            $scope.urltitle = $rootScope.filelistimg[key]['title'];
        }

        // watch title change
        $scope.$watch('urltitle', function(nv, ov) {
            if ($scope.delsignimg == 1) {
                $rootScope.filelistimg[$scope.keyimg]['title'] = $scope.urltitle;
                $scope.multipleimgarticalimg();
            }
        });

        // first img of url tab
        $scope.multipleimgarticalimg = function() {
            if ($scope.filelistimg[0].img) {
                var str = '<div class="coverimg">' +
                    '<div class="covertext" ng-click="tabpreviewimg(0)">' +
                    '<div ng-repeat="(k,v) in filelistimg">' +
                    '<img ng-if="k == 0" ngf-src="v.img" />' +
                    '<div class="covertitle" ng-if="k == 0">{{v.title}}</div>' +
                    '</div>' +
                    '</div>';
            } else {
                var str = '<div class="coverimg">' +
                    '<div class="covertext"  ng-click="tabpreviewimg(0)">' +
                    '<p>封面图片</p>' +
                    '<p>推荐尺寸:900像素*500像素</p>' +
                    '</div>' +
                    '<div ng-repeat="(k,v) in filelistimg">' +
                    '<div class="covertitle" ng-if="k == 0">{{v.title}}</div>' +
                    '</div>' +
                    '</div>';
            }
            var $html = $compile(str)($scope);
            $('#top3').html($html);
        }

        // watch title change
        $scope.$watch('urlabstract', function(nv, ov) {
            if ($scope.delsignimg == 1)
                $rootScope.filelistimg[$scope.keyimg]['abstract'] = $scope.urlabstract;
        });

        // watch title change
        $scope.$watch('outerUrl', function(nv, ov) {
            if ($scope.delsignimg == 1)
                $rootScope.filelistimg[$scope.keyimg]['url'] = $scope.outerUrl;
        });

        // watch checked change
        $scope.$watch('thirdchecked', function(nv, ov) {
            if ($scope.delsignimg == 1) {
                if ($scope.thirdchecked) {
                    $rootScope.filelistimg[$scope.keyimg]['is_checked'] = $scope.thirdchecked;
                } else {
                    $rootScope.filelistimg[$scope.keyimg]['is_checked'] = 0;
                }
            }
        });

        // delete img upload
        $scope.deleteShowItemimg = function($event, key) {
            $scope.delsignimg = 2;
            $scope.previewfileimg = '';
            $scope.urltitle = '';
            $scope.urlabstract = '';
            $scope.outerUrl = '';
            $('#addthirdtabchk').prop('checked', false);
            $rootScope.filelistimg.splice(key, 1);
            $($event.target).closest('.show_item').remove();
            $('#items3').empty();
            for (var i = 1; i < $rootScope.filelistimg.length; i++) {
                $scope.key = i;
                var str = '<div class="show_item" ng-click="tabpreviewimg(' + i + ')">' +
                    '<div class="box clearfix">' +
                    '<div ng-repeat="(k,v) in filelistimg">' +
                    '<div class="title fl" ng-if="k == ' + i + '">{{v.title}}</div>' +
                    '<img class="img" ng-if="k == ' + i + '" ngf-src="v.img" />' +
                    '</div>' +
                    '</div>' +
                    '<div class="item_action">' +
                    '<i class="large trash icon" ng-click="deleteShowItemimg($event,' + i + ')"></i>' +
                    '</div>' +
                    '</div>';
                var $html = $compile(str)($scope);
                $('#items3').append($html);
            }
            $('#bottom3').show();
        }

        // clear the value of ng-model
        $scope.initvalueoffivetabmodel = function() { //why clear function doesn't run
            $scope.urltitle = '';
            $scope.urlabstract = '';
            $scope.outerUrl = '';
            $('#addthirdtabchk').prop('checked', false);
        }

        // delete third tab img
        $scope.delthirdimg = function() {
            $rootScope.filelistimg[$scope.keyimg]['img'] = '';
            $scope.previewfileimg = '';
        }

        // display fisrt picture
        $scope.thirdtabcheckbox = function() {
            if ($("input[name='addthirdtabchk']").prop('checked')) {
                $scope.thirdchecked = 1;
            } else {
                $scope.thirdchecked = 0;
            }
        }

        // temp radio click event
        $scope.tempradioevent = function() {
            if ($('#temporarytime').prop('checked')) {
                $scope.chk.tempradiochk = 1;
                $scope.chk.regularradiochk = 0;
            } else {
                $scope.chk.tempradiochk = 0;
                $scope.chk.regularradiochk = 1;
            }
        }

        // regular raido  click event
        $scope.regradioevent = function() {
            if ($('#regulartime').prop('checked')) {
                $scope.chk.regularradiochk = 1;
                $scope.chk.tempradiochk = 0;
            } else {
                $scope.chk.regularradiochk = 0;
                $scope.chk.tempradiochk = 1;
            }
        }

        // safe checkbox event
        $scope.safechkbox = function() {
            if ($('#secret').prop('checked')) {
                $scope.safechk = 1;
            } else {
                $scope.safechk = 0;
            }
        }
    })
})